package com.cskaoyan.service.wx;

import com.cskaoyan.bean.Address;
import com.cskaoyan.bean.AddressExample;
import com.cskaoyan.mapper.AddressMapper;
import com.cskaoyan.mapper.RegionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author heyyon
 */
@Service
public class WxAddressServiceImpl implements WxAddressService{
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    RegionMapper regionMapper;
    @Override
    public List<Address> list(Integer userId) {
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria=addressExample.createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        return addresses;
    }

    @Override
    public Address detail(Integer id) {
        Address address=addressMapper.selectById(id);
        int provinceId=address.getProvinceId();
        int cityId=address.getCityId();
        int areaId=address.getAreaId();
        String provinceName = regionMapper.selectNameById(provinceId);
        String cityName= regionMapper.selectNameById(cityId);
        String areaName= regionMapper.selectNameById(areaId);
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);
        return address;
    }

    @Override
    public int save(Address address,Integer userId) {
        AddressExample addressExample=new AddressExample();
        Integer id=address.getId();
        AddressExample.Criteria criteria=addressExample.createCriteria();
        if (id != 0) {
            criteria.andIdEqualTo(id);
        }
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        //增加或修改地址时，若默认地址isdefault为ture，则清除该用户其他行的isdefault状态
        if (address.getIsDefault()) {
            addressMapper.clearOtherIsDefault(userId);
        }
        int row=0;
        long l = addressMapper.countByExample(addressExample);
        List<Address> addresses=null;
        if (l != 0) {
            addresses=addressMapper.selectByExample(addressExample);
            addressMapper.deleteById(id);
        }
        if (id!=0) {
            address.setAddTime(addresses.get(0).getAddTime());
        } else {
            address.setAddTime(new Date());
        }
        address.setUserId(userId);
        row=addressMapper.insertSelective(address);
        return row;
    }

    @Override
    public int delete(Integer id) {
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria=addressExample.createCriteria();
        if (id != null) {
            criteria.andIdEqualTo(id);
        }
        int i = addressMapper.deleteByExample(addressExample);
        return i;
    }
}
